package yoshop_ast

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"os"
	"path/filepath"
	"strconv"

	"gitee.com/libs_2/yoshop_ast/model"
	nanoid "github.com/matoous/go-nanoid/v2"
)

// GetFileGroups 获取文件存储分组列表
func (c *Client) GetFileGroups(ctx context.Context) (model.GetFileGroupsResponse, error) {
	var res model.GetFileGroupsResponse
	body, err := c.doPost(ctx, "/index.php?s=/store/files.group/list", nil)
	if err != nil {
		return res, err
	}

	err = json.Unmarshal(body, &res)
	if err != nil {
		return res, err
	}

	if res.Status != 200 {
		return res, errors.New(res.Msg)
	}
	return res, nil
}

// Upload 上传文件
func (c *Client) UploadImageFile(ctx context.Context, filePath string, groupId int, isRename bool) (model.UploadResponse, error) {
	var res model.UploadResponse

	// 构建multipart form数据
	formData := map[string]string{
		"groupId": strconv.Itoa(groupId),
	}

	// 打开文件
	file, err := os.Open(filePath)
	if err != nil {
		return res, err
	}
	defer file.Close()

	var fn = ""
	if isRename {
		ext := filepath.Ext(filePath)
		fn, _ = nanoid.New()
		fn = fn + ext
	} else {
		fn = filepath.Base(file.Name())
	}
	// 发送请求
	body, err := c.doPostFile(ctx, "/index.php?s=/store/upload/image", file, "iFile", fn, formData)
	if err != nil {
		return res, err
	}

	// 解析响应
	err = json.Unmarshal(body, &res)
	if err != nil {
		return res, err
	}

	if res.Status != 200 {
		return res, errors.New(res.Msg)
	}
	return res, nil
}

// DeleteFiles 删除文件内容
func (c *Client) DeleteFiles(ctx context.Context, fileIds ...int64) error {
	reqBody, _ := json.Marshal(map[string][]int64{
		"fileIds": fileIds,
	})

	body, err := c.doPost(ctx, "/index.php?s=/store/files/delete", bytes.NewReader(reqBody))
	if err != nil {
		return err
	}

	var res model.CommonResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		return err
	}

	if res.Status != 200 {
		return errors.New(res.Msg)
	}

	return nil
}
